<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\Base;
use App\Model\ArticleTag;
use App\Model\Tag;
use Laravel\Scout\Searchable;
class Article extends Base
{
    //use Searchable;
    public function toSearchableArray()
    {
        return [
            'title' => $this->title,
            'markdown' => $this->markdown,
            'keywords'=>$this->keywords
        ];
    }
    //
    protected $guarded=[];
    public  function tags(){
        return $this->belongsToMany(Tag::class,'article_tags','article_id','tag_id');
    }
    public  function comments(){
        return $this->hasMany(ArticleComment::Class,'article_id','id');
    }
    public  function zans(){
        return $this->hasMany(Zan::Class,'article_id','id');
    }
    /**
     * 搜索文章获取文章id
     *
     * @param $wd
     *
     * @return \Illuminate\Support\Collection
     */
    public function searchArticleGetId($search)
    {
        // 如果 SCOUT_DRIVER 为 null 则使用 sql 搜索
//        if (is_null(env('SCOUT_DRIVER'))) {
//
//            $id = Article::where('title','like', "%$search%")
//                ->orWhere('keywords', 'like', "%$search%")
//                ->orWhere('content', 'like', "%$search%")
//                ->orWhere('markdown', 'like', "%$search%")
//                ->pluck('id');
//            return $id;
//        }

        // 如果全文搜索出错则降级使用 sql like
        try{
            $id = Article::search($search)->keys();
        } catch (\Exception $e) {
            $id = Article::where('title','like', "%$search%")
                ->orWhere('keywords', 'like', "%$search%")
                ->orWhere('content', 'like', "%$search%")
                ->orWhere('markdown', 'like', "%$search%")
                ->pluck('id');
        }
        return $id;
    }
}
